package com.zp.self.module.编程测试.树型结构构建;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author By ZengPeng
 * @Description
 * @date in  2021/4/9 14:03
 * @Modified By
 */
public class TreeTest {

    @Test
    public void  treeTest(){
        List<Tree> trees = new ArrayList<>();
        trees.add(new Tree().setId(1).setName("a").setPid(2));
        trees.add(new Tree().setId(2).setName("b").setPid(3));
        trees.add(new Tree().setId(3).setName("c").setPid(null));
        trees.add(new Tree().setId(4).setName("d").setPid(3));

        //遍历，构造集合
        Map<Integer,List<Tree>> map = new HashMap<>();
        for (Tree tree : trees) {
            List<Tree> children ;
            if(map.containsKey(tree.pid)){
                children = map.get(tree.pid);
            }else{
                children = new ArrayList<>();
            }
            children.add(tree);
            map.put(tree.pid,children);
        }

        //遍历，构建树
        for (int i = 0; i < trees.size(); i++) {
            Tree tree = trees.get(i);
            if(tree.pid!=null){
               trees.remove(i);//移除非根节点
               i--;
            }
            tree.setChild(map.get(tree.id));
        }
        System.out.println(trees);
    }
}

